package cn.bugstack.domain.strategy.service.rule.chain.impl;
import cn.bugstack.domain.strategy.repository.IStrategyRepository;
import cn.bugstack.domain.strategy.service.armory.IStrategyDispatch;
import cn.bugstack.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.bugstack.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.bugstack.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 19872
 * 权重责任链节点
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;
    @Resource
    protected IStrategyDispatch strategyDispatch;



    @Override
    public DefaultChainFactory.StrategyAwardVo logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId：{} strategyId：{} ruleModel：{}", userId, strategyId, ruleModel());
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());

        //1.根据用户ID查询用抽奖消耗的积分值，本章先写死为固定值。后续需要从数据库中查询
        List<Long> analyticalValueGroup = getAnalyticalValue(ruleValue);

        if (analyticalValueGroup == null || analyticalValueGroup.isEmpty()) {
            return null;
        }
        Collections.sort(analyticalValueGroup);
        Collections.reverse(analyticalValueGroup);
        Integer userScore = repository.queryActivityAccountTotalUseCount(userId, strategyId);
        //2.默认排序
        Long nextValue = analyticalValueGroup.stream()
                .filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);

        if (nextValue != null) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, String.valueOf(nextValue));
            log.info("抽奖责任链-权重接管 userId：{} strategyId：{} ruleModel：{} awardId：{}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVo.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }

        // 5. 过滤其他责任链
        log.info("抽奖责任链-权重放行 userId：{} strategyId：{} ruleModel：{}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }

    private List<Long> getAnalyticalValue(String ruleValue) {
        List<Long> analyticalValueGroup = new ArrayList<>();
        String[] splitValues = ruleValue.split(Constants.SPACE);
        for (String splitValue : splitValues) {
            if (splitValue == null || splitValue.isEmpty()) {
                return analyticalValueGroup;
            }
            String[] splits = splitValue.split(Constants.COLON);
            if (splits.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + splitValue);
            }
            analyticalValueGroup.add(Long.parseLong(splits[0]));
        }
        return analyticalValueGroup;
    }
}
